package br.com.Login.controller.filtros;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import br.com.Login.controller.SessaoUserInterface;

public class FiltroVerificaLogado implements Filter{

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		try {
			SessaoUserInterface u = (SessaoUserInterface)Class.forName(request.getServletContext().getInitParameter("sessao_usuario")).newInstance();

			if(u == null || u.getUser() == null || u.getLoggedin() == false){
				String contextPath = request.getServletContext().getContextPath();
				HttpServletResponse r = (HttpServletResponse) response;
				r.sendRedirect(contextPath+"/login.xhtml");			
			}else{
				chain.doFilter(request, response);
			}

		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
}
